"""User routes."""
from flask import request
from flask_restx import Namespace, Resource, fields
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models.user import User

api = Namespace('user', description='User operations')

# Models
home_location_model = api.model('HomeLocation', {
    'latitude': fields.Float(required=True),
    'longitude': fields.Float(required=True),
    'accuracy': fields.Float(required=True)
})

user_profile_model = api.model('UserProfile', {
    'id': fields.String(description='User ID'),
    'wechat_openid': fields.String(description='WeChat OpenID'),
    'nickname': fields.String(description='User nickname'),
    'avatar_url': fields.String(description='Avatar URL'),
    'home_location': fields.Raw(description='Home location'),
    'preferences': fields.Raw(description='User preferences'),
    'created_at': fields.String(description='Account creation time')
})


@api.route('/profile')
class UserProfile(Resource):
    """User profile endpoint."""
    
    @jwt_required()
    @api.marshal_with(user_profile_model)
    def get(self):
        """Get user profile.
        
        Validates: Requirements 4.1
        """
        user_id = get_jwt_identity()
        user = User.query.get(user_id)
        
        if not user:
            api.abort(404, 'User not found')
        
        return user.to_dict(), 200


@api.route('/home-location')
class HomeLocation(Resource):
    """Home location endpoint."""
    
    @jwt_required()
    @api.expect(home_location_model)
    def put(self):
        """Update user's home location.
        
        Validates: Requirements 4.1
        """
        user_id = get_jwt_identity()
        user = User.query.get(user_id)
        
        if not user:
            api.abort(404, 'User not found')
        
        data = request.get_json()
        
        # Validate location data
        latitude = data.get('latitude')
        longitude = data.get('longitude')
        accuracy = data.get('accuracy')
        
        if latitude is None or longitude is None or accuracy is None:
            api.abort(400, 'latitude, longitude, and accuracy are required')
        
        # Validate ranges
        if not (-90 <= latitude <= 90):
            api.abort(400, 'latitude must be between -90 and 90')
        
        if not (-180 <= longitude <= 180):
            api.abort(400, 'longitude must be between -180 and 180')
        
        if accuracy <= 0:
            api.abort(400, 'accuracy must be greater than 0')
        
        # Update user's home location
        user.home_latitude = latitude
        user.home_longitude = longitude
        user.home_accuracy = accuracy
        
        db.session.commit()
        
        return {
            'message': 'Home location updated successfully',
            'home_location': {
                'latitude': user.home_latitude,
                'longitude': user.home_longitude,
                'accuracy': user.home_accuracy
            }
        }, 200
